package com.hq.base.web;

import com.hq.admin.domain.Operator;
import com.hq.base.domain.BaseUser;
import com.hq.common.domain.*;
import com.hq.common.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @since 2015-01-22 21:46
 */
@Controller
public class TokenInterceptor extends HandlerInterceptorAdapter {
    private final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        String loginUrl;
        boolean isAdmin = url.contains("/admin/");
        if (isAdmin) {
            loginUrl = "/modules/admin/login.jsp";
        } else {
            loginUrl = "/modules/user/login.jsp";
        }
        try {
            if (isAdmin) {
                Object object=request.getSession().getAttribute(Const.Operator_Session);
                Operator user = object==null?null:(Operator)object;
                if (user == null) {
                    if (url.contains("mvc")) {
                        response.sendRedirect(request.getContextPath() + loginUrl);
                    } else {
                        this.responseWrite(response, new Result(ResultCode.PRECONDITION_FAILED, loginUrl, "未登录或者登陆超时，点击确定将跳至登陆页面。"));
                    }
                    return false;
                }
                ContextHolder.getOperatorContext().setOperator(user);
            } else {
                Object object=request.getSession().getAttribute(Const.User_Session);
                BaseUser user = object==null?null:(BaseUser)object;
                if (user == null) {
                    if (url.contains("mvc")) {
                        response.sendRedirect(request.getContextPath() + loginUrl);
                    } else {
                        this.responseWrite(response, new Result(ResultCode.PRECONDITION_FAILED, loginUrl, "未登录或者登陆超时，点击确定将跳至登陆页面。"));
                    }
                    return false;
                }
                ContextHolder.getUserContext().setUser(user);
            }
        } catch (Exception e) {
            logger.error("校验权限异常", e);
            if (url.contains("mvc")) {
                response.sendRedirect(request.getContextPath() + loginUrl);
            } else {
                this.responseWrite(response, new Result(ResultCode.PRECONDITION_FAILED, loginUrl, "未登录或者登陆超时，点击确定将跳至登陆页面。"));
            }
            return false;
        }
        return true;
    }

    private void responseWrite(HttpServletResponse response, Result result) {
        try {
            if (result != null) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json");
                String strResult = JsonUtil.writeValueAsString(result);
                response.getWriter().write(strResult);
                response.flushBuffer();
            }
        } catch (IOException e) {
            logger.error("报文输出异常!");
        }
    }
}
